<?php
/**
 * @package     CiMS.framework
 *
 * @copyright   Copyright (C) 2012 Cimaron Shanahan. All rights reserved.
 * @license     http://opensource.org/licenses/mit-license.php MIT License
 */
defined('CiMS') or die;


/**
 * CiMS URI Class
 */
class CiMSUri extends CiMSObject {
	
	/**
	 * Override CiMSObject::getInstance()
	 */
	public static function getInstance($uri = NULL) {
		return parent::getInstance($uri ? array('uri' => $uri) : array());
	}

	/**
	 * Parse a URI
	 */
	public static function parse($uri = NULL) {
		$results = parse_url($uri ? $uri : self::getCurrent());
		return $results;
	}

	/**
	 * Get Current URI
	 */
	public static function getCurrent() {
		static $current;

		if (is_null($current)) {

			$scheme = (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
			
			if (!empty($_SERVER['PHP_SELF']) && !empty($_SERVER['REQUEST_URI'])) {
				//Apache
				$current = $scheme . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
			} else {
				//IIS
				$current = $scheme . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
				if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
					$current .= '?' . $_SERVER['QUERY_STRING'];
				}
			}			
		}

		return $current;
	}

	/**
	 * Constructor
	 */
	public function __construct($config = array()) {
		if (!isset($config['uri'])) {
			$config['uri'] = self::getCurrent();
		}
		parent::__construct($config);
		$parts = self::parse($this->get('uri'));

		foreach ($parts as $key => $value) {

			$data = false;

			if ($key == 'path') {
				$data = explode('/', substr($value, 1));
			}

			if ($key == 'query') {
				parse_str($value, $data);
			}

			if ($data) {
				$value = new CiMSObject();
				foreach ($data as $k => $v) {
					$value->set($k, $v);
				}
			}

			$this->set($key, $value);
		}
	}

	
}

